import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username, password: password }).then(response => {
        const { data, headers } = response
        const avatar = 'https://i.postimg.cc/wTSBP7cp/79225008-p0.jpg'
        const role = []
        data.data.role.forEach(item => {
          role.push(item.role_name)
        })
        sessionStorage.userInfo = JSON.stringify({
          'user_name': data.data.username,
          'role_name': role,
          'avatar': avatar
        })

        commit('SET_TOKEN', headers.token)
        commit('SET_NAME', data.data.username)
        commit('SET_AVATAR', avatar)
        setToken(headers.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    const userInfo = sessionStorage.userInfo
    let data = null
    if (userInfo) {
      data = JSON.parse(userInfo)
    }

    return new Promise((resolve, reject) => {
      if (!data) {
        reject('Verification failed, please Login again.')
      }
      commit('SET_ROLES', data.role_name)
      commit('SET_NAME', data.name)
      commit('SET_AVATAR', data.avatar)
      resolve(data)
    })
  },

  // user logout
  logout({ commit, state }) {
    sessionStorage.removeItem('userInfo')
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

